import React from 'react'
import { Table,Icon,Modal,Popconfirm,Button,Message,Row,Col} from 'antd';
import officeApi from '../../../api/office';
import areaApi from '../../../api/area';

import PanelBox from '../../../components/PanelBox';
import OfficeForm from '../../Form/Office';
import './index.less'
import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    resData:[],
    loading: false,
    pagination:false,
    defaultExpandAllRows:true,
    isOpenCreateOffice: false,
    isOpenEditOffice: false,
    parentOffice:null,
    office:null,
    areaParentIds:null,
    cascaderAreaData:[]
  };


  columns = [{
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: '15%',
  }, {
    title: '机构地址',
    dataIndex: 'address',
    key: 'address',
    width: '20%',
  }, {
    title: '机构类型',
    dataIndex: 'type',
    key: 'type',
    width: '15%',
    render: (text, record) => {
      switch(record.type){
        case '1':
          return (<span>代理商</span>);
        case '2':
          return (<span>分销商</span>);
        case '3':
          return (<span>物业</span>);
        default:
          break;
      }
      return ;
    }
  }, {
    title: '负责人',
    dataIndex: 'master',
    key: 'master',
    width:'15%'
  }, {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
    width:'15%'
  }, {
    title: '操作',
    dataIndex: 'action',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.startUpdate.bind(this,record)}>编辑</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除该分销商?" data-id={record.key} onConfirm={this.dele.bind(this,record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];
  
  componentDidMount = () =>{
    this.initData();
  }

  initData = () => {
    let user = this.props.profile.user;
    let officeAreaId = user.officeAreaId;
    let officePId = user.officeId;

    this.setState({ loading: true });
    // 分页查看所有机构数据
    officeApi.get('/findChildrenOfficeByPId',{
      officePId:officePId,
      type:'3'
    }).then((res) => {
      const result = res.data.data;
      this.setState({
        resData: result,
      });
    });


    // 根据代理商机构id查看一级区域数据
    areaApi.get('/getAreaByParent', { id: officeAreaId }).then((data) => {
      const result = data.data.data;
      for(let i=0;i<result.length;i++){
        result[i] = {
          value:result[i].id,
          label:result[i].name,
          isLeaf:result[i].type=='5'?true:false
        };
      }

      this.setState({
        loading: false,
        cascaderAreaData: result,
      });
    });
  }

  getAreaByParent = (pId) => {
    return new Promise((r,j) => {
      areaApi.get('/getAreaByParent', { id: pId}).then(data => {
        const result = data.data.data;
        let children = [];
        for(let k=0;k<result.length;k++){
          children.push({
            value:result[k].id,
            label:result[k].name,
            isLeaf:false
          });
        }
        r(children);
      });
    });
  }

  queryAllNodeChildren = (areaIds) => {
    let promiseAry = [];
    for(let i=0;i<areaIds.length-1;i++){
      promiseAry.push(this.getAreaByParent(areaIds[i]));
    }
    return Promise.all(promiseAry);
  }

  cascaderQuery = (areaIds) => {
    return new Promise((r,j) => {
      this.queryAllNodeChildren(areaIds).then(selectAreaChildrenAry => {
        let cascaderAreaData = this.state.cascaderAreaData;
        let currentData = null;
        for(let i=0;i<areaIds.length-1;i++){
          if(currentData != null){
            for(let j=0;j<currentData.children.length;j++){
                if(currentData.children[j].value == areaIds[i]){
                  currentData = currentData.children[j];
                  currentData.children = selectAreaChildrenAry[i];
                }
            }
          }else{
            for(let n=0;n<cascaderAreaData.length;n++){
                if(cascaderAreaData[n].value == areaIds[i]){
                  currentData = cascaderAreaData[n];
                  currentData.children = selectAreaChildrenAry[i];
                }
            }
          }
        }

        r(cascaderAreaData);
      });
    });
  }

  startCreate = (record,event) =>{
    let user = this.props.profile.user;
    record = {
      id:user.officeId,
      name:user.officeName
    };

    if(this.resetFields){
      this.resetFields();
      this.resetAgentType();
    }

    this.setState({
      parentOffice:record,
      office:{
        type:'3'
      },
      isOpenCreateOffice: true
    });
  }
  startUpdate = async (record,event) =>{
    let officeAreaId = this.props.profile.user.officeAreaId;

    if(this.resetFields)this.resetFields();
    let areaParentIds = record.areaParentIds.split(',');
    areaParentIds.shift();
    areaParentIds.shift();
    areaParentIds.pop();
    areaParentIds.push(record.areaId);
    
    //把当前最前一级之前的全部删除掉
    for(let i=0;i<areaParentIds.length;i++){
      if(officeAreaId == areaParentIds[i]){
        let count = i + 1;
        for(let j=0;j<count;j++){
          areaParentIds.shift();
        }
        break;
      }
    }

    Promise.all([officeApi.get('getAgentTypeByOfficeId',{officeId:record.id}),this.cascaderQuery(areaParentIds)]).then(([agentTypes,cascaderAreaData]) => {
      if(agentTypes.data.data){
        record.agentTypes = agentTypes.data.data;
      }

      this.setState({
        cascaderAreaData:cascaderAreaData,
        isOpenEditOffice: true,
        office:record,
        areaParentIds:areaParentIds
      });
    });   
  }
  close = () => {
    this.setState({
      isOpenEditOffice: false,
      isOpenCreateOffice: false,
    });
    this.initData();
  }
  dele = (id,event) => {
    officeApi.delete('/delOffice', {id:id}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.initData();
     }else{
      Message.error(result.message);
     }
    });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
    this.resetAgentType = params.resetAgentType;
    this.clearIcon = params.clearIcon;
  }

  render() {
    return (
      <div>
        <Row style={{marginBottom:'10px'}} type="flex" justify="start">
          <Col style={{width:'auto',lineHeight:'28px'}}>
            <Button type="primary" icon="plus" onClick={this.startCreate}>添加新物业</Button>
          </Col>
        </Row>
        <PanelBox>
        {this.state.resData && this.state.resData.length ? 
          <Table columns={this.columns} rowKey={'id'} dataSource={this.state.resData} loading={this.state.loading} pagination={this.state.pagination} 
          defaultExpandAllRows={true} />  :  ' ' }
        </PanelBox>
        <Modal
          title="创建物业"
          visible={this.state.isOpenCreateOffice}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="800"
          style={{height:'auto'}}
          footer={null}
        >
          <OfficeForm isProperty={true} areaData={this.state.cascaderAreaData} profile={this.props.profile} parentOffice={this.state.parentOffice} office={this.state.office} close={this.close} callbackParent={this.initChildrenParams}/>
        </Modal>
        <Modal
          title="修改物业"
          visible={this.state.isOpenEditOffice}
          onCancel={this.close}
          wrapClassName="vertical-center-modal"
          width="800"
          footer={null}
        >
          <OfficeForm isProperty={true} areaParentIds={this.state.areaParentIds} profile={this.props.profile} areaData={this.state.cascaderAreaData} office={this.state.office} close={this.close} callbackParent={this.initChildrenParams} />
        </Modal>
      </div>
    );
  }
}
